package com.itheima.utils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class GetAge {
    //通过生日算年龄(用当前时间减去生日时间)
    public static int getAgeByBirth(Date birthDay) throws ParseException {
        int age = 0;
        //获取当前时间
        //Calendar cal = Calendar.getInstance();
        //不传参数默认获取当前时间
        Calendar calendar = new GregorianCalendar();
        //出生日期晚于当前时间，无法计算
        if (calendar.before(birthDay)) {
            throw new IllegalArgumentException(
                    "你还没出生呢,等你出生了再来吧");
        }
        int yearNow = calendar.get(Calendar.YEAR);  //当前年份

        int monthNow = calendar.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = calendar.get(Calendar.DAY_OF_MONTH); //当前日期

        calendar.setTime(birthDay);//将客户生日赋值给Calendar类

        int yearBirth = calendar.get(Calendar.YEAR);//获得客户生日年分

        int monthBirth = calendar.get(Calendar.MONTH);//获得客户生日月份
        int dayOfMonthBirth = calendar.get(Calendar.DAY_OF_MONTH);//获得日
        age = yearNow - yearBirth;  //用现在的年分减去客户出生的年分
        //计算客户的虚岁
        //如果本年的生日还没过,则年龄减一
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        //返回计算出的客户年龄
        return age;
    }

}
